package com.lenovo.testreport.user.controller;

import com.lenovo.testreport.user.model.Feedback;
import com.lenovo.testreport.user.model.MessageCenter;
import com.lenovo.testreport.user.model.Userinfo;
import com.lenovo.testreport.user.service.MessageService;
import com.lenovo.testreport.user.service.UserService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * @author CJF
 * @date 2018/10
 * <p>
 * 用户反馈表的操作
 */
@Controller
@RequestMapping("/Question")
public class Question {

    @Autowired
    private UserService userService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private RedisTemplate redisTemplate;

    //新增用户反馈
    @RequestMapping("/AddQuestion")
    public @ResponseBody
    String AddQuestion(HttpServletRequest request) {

        Feedback question = new Feedback();
        question.setUsername(request.getParameter("name"));
        question.setTitle(request.getParameter("title"));
        question.setContent(request.getParameter("content"));
        question.setType(request.getParameter("questiontype"));
        question.setVersion(request.getParameter("version"));
        question.setUseraccount(request.getSession().getAttribute("User").toString());

        Date now = new Date();
        String time = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(now);
        question.setPosttime(time);
        int result = userService.addQuestion(question);
        messageService.AddMessageRecord(new MessageCenter(request.getSession().getAttribute("User").toString(), "增加了一条反馈", "question-normal"));

        return "提交成功！";
    }

    //查看所有用户反馈
    @RequestMapping("/AllQuestion")
    public @ResponseBody
    Object AllQuestion(HttpServletRequest request) {

        return userService.finAllQuestion();

    }

    //更新反馈的处理状态
    @RequestMapping("/UpateQuestion")
    public @ResponseBody
    String UpateQuestion(HttpServletRequest request) {
        int tid = Integer.valueOf(request.getParameter("tid"));
        String status = request.getParameter("status");
        Feedback feedback = userService.FindQuestionById(tid);
        feedback.setStatus(status);

        int result = userService.updateQuestion(feedback);
        if (result > 0) {
            return "状态改变成功！";
        } else {
            return "状态改变失败！";
        }
    }

    //更新反馈BUG地址
    @RequestMapping("/UpateQuestionBugUrl")
    public @ResponseBody
    String UpateQuestionBugUrl(HttpServletRequest request) {

        int tid = Integer.valueOf(request.getParameter("tid"));
        String bugurl = request.getParameter("bugurl");
        Feedback feedback = userService.FindQuestionById(tid);
        feedback.setBugurl(bugurl);
        int result = userService.updateQuestion(feedback);
        if (result > 0) {
            return "BUG地址修改成功！";
        } else {
            return "BUG地址修改失败！";
        }
    }

    //用户查看我的反馈
    @RequestMapping("/FindQuestionByName")
    public @ResponseBody
    Object FindQuestionByName(HttpServletRequest request) {
        String name = ((Userinfo) redisTemplate.opsForValue().get("Lenovo-sessionId:" + request.getSession().getId())).getUsername();
        List<Feedback> list = userService.finQuestionByName(name);

        return list;
    }

    //管理员将反馈以邮件形式发出
    @RequestMapping("/SendEmail")
    public @ResponseBody
    String SendEmail(HttpServletRequest request) throws AddressException, MessagingException {

        String emailsurl = request.getParameter("email");
        String tid = request.getParameter("tid");
        Feedback question = userService.findquestionByID(Integer.valueOf(tid));

        String[] emails = emailsurl.split(",");

        List list = new ArrayList();
        for (int i = 0; i < emails.length; i++) {
            list.add(new InternetAddress(emails[i]));
        }

        InternetAddress[] address = (InternetAddress[]) list.toArray(new InternetAddress[list.size()]);

        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");// 连接协议
        properties.put("mail.smtp.host", "smtp.qq.com");// 主机名
        properties.put("mail.smtp.port", 465);// 端口号
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
        properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息

        // 得到回话对象
        Session session = Session.getInstance(properties);
        // 获取邮件对象
        Message message = new MimeMessage(session);
        // 设置发件人邮箱地址
        message.setFrom(new InternetAddress("Chenjf@lenovocloud.com"));
        // 设置收件人邮箱地址
        //message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress(emailurl)});//一个收件人
        message.setRecipients(Message.RecipientType.TO, address);
        // 设置邮件标题
        message.setSubject("用户反馈 :" + question.getTitle());
        // 设置邮件内容
        message.setText(question.toString());
        // 得到邮差对象
        Transport transport = session.getTransport();
        // 连接自己的邮箱账户
        transport.connect("Chenjf@lenovocloud.com", "Q13145241q");// 密码为QQ邮箱开通的stmp服务后得到的客户端授权码
        // 发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

        messageService.AddMessageRecord(new MessageCenter(request.getSession().getAttribute("User").toString(), "将 " + question.getTitle() + " 该条用户反馈发送给了 " + emailsurl, "email-admin-question"));

        return "发送成功!";
    }
}
